from rest_framework import serializers
from django.contrib.auth import models
from rest_framework.exceptions import ValidationError
import re
from rest_framework_jwt.utils import jwt_encode_handler,jwt_payload_handler

class LoginSerializers(serializers.ModelSerializer):
    username=serializers.CharField()
    class Meta:
        model=models.User
        fields = ['username', 'password']

    def validate(self, attrs):
        username=attrs.get('username')
        password=attrs.get('password')

        if re.match('^1[3-9][0-9]{9]$',username):
            user=models.User.objects.filter(mobile=username).first()

        elif re.match('^.+@.+$',username):
            user=models.User.objects.filter(email=username).first()

        else:
            user= models.User.objects.filter(username=username).first()


            if user:
                if user.check_password(password):
                    payload=jwt_payload_handler(user)
                    token=jwt_payload_handler(payload)
                    self.context['token'] = token
                    self.context['username'] = user.username
                    return attrs
                else:
                    raise ValidationError('密码错误')
            else:
                raise ValidationError('用户不存在')


import re
from datetime import datetime, timedelta
from mytest.settings import REGEX_MOBILE
# from users.models import VerifyCode
from rest_framework import serializers
from django.contrib.auth import get_user_model

User = get_user_model()


class SmsSerializer(serializers.Serializer):
    mobile = serializers.CharField(max_length=11)

    # 函数名必须：validate + 验证字段名
    def validate_mobile(self, mobile):
        """
        手机号码验证
        """
        # 是否已经注册
        if User.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError("用户已经存在")

        # 是否合法
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError("手机号码非法")

        # # 验证码发送频率
        # # 60s内只能发送一次
        # one_mintes_ago = datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
        # if VerifyCode.objects.filter(add_time__gt=one_mintes_ago, mobile=mobile).count():
        #     raise serializers.ValidationError("距离上一次发送未超过60s")

        return mobile